// packageRevisit/pages/list/index.js
import {getList, saveAnswer} from "../../../service/Revisit";
import Dialog from "@vant/weapp/dialog/dialog";
import Toast from "@vant/weapp/toast/toast";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        pageShow: false,
        list: [],
        isLoading: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getList()
    },

    /*
    * 获取列表信息
    * */
    getList: async function () {
        try {
            let res = await getList();
            this.setData({
                list: res.map(function (item) {
                    return {
                        title: item.title,
                        current: 0
                    }
                }),
                pageShow: true
            })
        } catch (e) {
            console.error(e)
        }
    },

    /*
    * 单选框change
    * */
    onChange: async function (e) {
        let index = e.currentTarget.dataset.index;
        let list = this.data.list;
        let value = e.detail;
        let current = list[index].current;
        if (current === value) return false;
        this.setData({["list[" + index + "].current"]: value});
        if (index !== list.length - 1) { //不是最后一题
            if (value == 1) return false;
        } else {
            if (value == 2) return false;
        }
        await Dialog.alert({
            title: "提示",
            message: "您的回答可能与真实情况不符，请与工作人员联系，或重新作答。"
        });
        this.setData({["list[" + index + "].current"]: 0});
    },

    /*
    * 提交
    * */
    onSubmit: async function () {
        try {
            let isLoading = this.data.isLoading;
            let list = this.data.list;
            let findInx = list.findIndex(function (item) {
                return item.current === 0
            })
            if (findInx >= 0) { //有未选中项
                await Dialog.alert({
                    title: "提示",
                    message: "您还没有完成答题。"
                });
                return false
            } else if (isLoading) { //防重复
                return false
            }  else {
                this.setData({isLoading: true});
                let answer = list.map(function (item) {
                    return item.current
                })
                Toast.loading({
                    mask: true,
                    duration: 0, // 持续展示 toast
                    message: "提交中..."
                });
                await saveAnswer({answer});
                Toast.success({message:"提交成功"});
                setTimeout(function () {
                    wx.reLaunch({url: "/pages/home/index/index"});
                }, 300)
            }
        } catch (e) {
            Toast.fail({message: e.errMsg});
            console.error(e)
        } finally {
            this.setData({isLoading: false})
        }
    }

})